<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div style="margin-bottom: 10px">
        <el-button slot="right" :loading="crud.loading" class="filter-item"
          :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'" size="mini" type="primary"
          @click="submit()">
          保存
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="warning"
                   @click="copyOrder" v-permission="permission.copy"
                   :disabled="crud.order.orderStatus !== 'SAVE'"
        >
          复制
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="success"
          :disabled="crud.order.orderStatus !== 'SAVE'" :loading="crud.passLoading"
          @click="crud.doDetailPassOrReject('PASS', id)">
          审核
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
          :disabled="crud.order.orderStatus !== 'PASS'" @click="crud.doDetailPassOrReject('REJECT', id)">
          反审
        </el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
          :disabled="$route.params.id == 'add'"
        >打印
        </el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
          :disabled="$route.params.id == 'add'"
        >打印预览
        </el-button>
        <el-button slot="right" :disabled="crud.order.orderStatus !== 'PASS'" class="filter-item" size="mini"
          type="info" :loading="crud.loading" @click="genrateFeeOrder">
          生成费用
        </el-button>
        <el-dialog title="确认信息" :visible.sync="confirmDialog" width="30%">
          <span>是否确认生成费用？</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="confirmDialog = false">取 消</el-button>
            <el-button type="primary" :loading="crud.loading" @click="confirmGenerate">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <el-form style="margin-bottom: 10px" size="small" label-width="120px" ref="orderForm" :rules="rules"
        :model="crud.order" >
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同开始时间" prop="startDate">
              <el-date-picker
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.startDate" format="yyyy - MM - dd" value-format="yyyy-MM-dd" type="date" style="width: 100%;" default-value
                placeholder="请选择合同开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同结束时间" prop="endDate">
              <el-date-picker
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.endDate" type="date" format="yyyy - MM - dd" value-format="yyyy-MM-dd" style="width: 100%;" default-value
                placeholder="请选择合同结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据编号">
              <el-input :disabled="true" v-model="crud.order.code" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同名称" prop="name">
              <el-input
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.name" placeholder="请输入合同名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同类型" prop="type">
              <el-select
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.type" class="filter-item" clearable placeholder="请选择合同类型" size="small"
                style="width: 100%;">
                <el-option v-for="item in dict.t_fee_order_type" :key="item.id" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="供应商">
              <zSelect :clearable="true" :value.sync="crud.order.supplierId == 0 ? null : crud.order.supplierId"
                :label="crud.order.supplierName" :showName="crud.order.supplierName"
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                url="api/dropDown/basCustomerList" :params="{ isContact: '1,2' }" style="width:  100%"
                @change="changeSupplier" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户">
              <zSelect
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                :clearable="true" :value.sync="crud.order.customerId == 0 ? null : crud.order.customerId"
                :showName="crud.order.customerName" url="api/dropDown/basCustomerList" :params="{ isContact: '0,2' }"
                style="width:  100%" @change="changeCustomer" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="返点方式">
              <el-select
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="rebaseType" class="filter-item" clearable placeholder="请选择返点方式" size="small"
                style="width: 100%;">
                <el-option v-for="item in dict.t_fee_rebate_type" :key="item.id" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="费用科目" prop="subjectId">
              <el-select-tree
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                placeholder="请选择内容" :data="subjects" :filterable="true" clearable
                v-model="crud.order.feeContractRebateDto.subjectId"
                :props="{ value: 'id', label: 'name', children: 'children' }" size="small" style="width: 100%;"
                @nodeClick="changeSubjects"></el-select-tree>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="取值对象" prop="valueType">
              <el-select
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.feeContractRebateDto.valueType" class="filter-item" clearable
                placeholder="请选择取值对象" size="small" style="width: 100%;">
                <el-option v-for="item in dict.t_fee_contract_value_type" :key="item.id + ''" :label="item.label"
                  :value="item.value + ''" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="满足条件" prop="reachItem">
              <el-select
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.feeContractRebateDto.reachItem" class="filter-item" :clearable="true"
                placeholder="请选择满足条件" size="small" style="width: 100%;" @change="changeReachItem">
                <el-option v-for="item in dict.t_fee_contract_reach_item" :key="item.id + ''" :label="item.label"
                  :value="item.value + ''" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="状态">
              <el-select :disabled="true" v-model="crud.order.orderStatus" class="filter-item" clearable
                placeholder="请选择状态" size="small" style="width: 100%;">
                <el-option v-for="item in dict.common_order_status" :key="item.id" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="备注">
              <el-input v-model="crud.order.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card>
            <div slot="header">
              <span>条件项目</span>
              <el-button :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                style="float: right;" type="primary" @click="addProject">
                新增
              </el-button>
            </div>
            <!--表格渲染-->
            <el-table ref="table" v-if="crud.order.feeContractRebateDto.reachItem == 2" stripe border
              v-loading="crud.loading" :data="crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList"
              size="small" style="width: 100%;">
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" width="60" label="序号" />
              <el-table-column v-if="columns.visible('goodsBrandCode')" prop="goodsBrandCode" label="编码" />
              <el-table-column v-if="columns.visible('goodsBrandName')" prop="goodsBrandName" label="名称">
                <template slot-scope="{row}">
                  <zSelect :value.sync="row.goodsBrandId" :showName="row.goodsBrandName" :filterable="true"
                    :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                     url="api/dropDown/basGoodsBrandList"
                    @change="changeReachBrands($event, row)" style="width:  100%" />
                </template>
              </el-table-column>
              <el-table-column v-if="columns.visible('barcode')" prop="barcode" label="条形码" />
              <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" align="center">
                <template slot-scope="scope">
                  <el-button slot="reference" class="el-icon-delete opration_icon_btn"
                    :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                    style="border: none;width: auto;height: auto" @click="delProjectGoodsRow(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-table ref="table" v-else stripe border v-loading="crud.loading"
              :data="crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList" size="small"
              style="width: 100%;">
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" width="60" label="序号" />
              <el-table-column v-if="columns.visible('goodsCode')" prop="goodsCode" label="编码" />
              <el-table-column v-if="columns.visible('goodsName')" prop="goodsName" label="名称">
                <template slot-scope="{row}">
                  <zSelect :value.sync="row.goodsId" :showName="row.goodsName"
                    :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                    :labelKey="'goodsName'" :valueKey="'goodsId'" url="/api/dropDown/basGoodsListForAdd"
                    :params="{ reachItem: crud.order.feeContractRebateDto.reachItem }"
                    @change="changeReachGoods($event, row)" style="width:  100%" />
                </template>
              </el-table-column>
              <el-table-column v-if="columns.visible('barcode')" prop="barcode" label="条形码" />
              <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" align="center">
                <template slot-scope="scope">
                  <el-button slot="reference" class="el-icon-delete opration_icon_btn"
                    :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                    style="border: none;width: auto;height: auto" @click="delProjectGoodsRow(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card>
            <div slot="header">
              <span>条件详情</span>
              <el-button :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                style="float: right;" type="primary" @click="addDetail">
                添加条件详情
              </el-button>
            </div>
            <!--表格渲染-->
            <el-table ref="table" stripe border v-loading="crud.loading"
              :data="crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList" size="small"
              style="width: 100%;">
              <el-table-column type="index" width="60" label="序号" />
              <el-table-column v-if="columns.visible('startAmount')" prop="startAmount" label="起始值（元）">
                <template slot-scope="{row}">
                  <el-input-number :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                    style="width:100%" v-model="row.startAmount" :precision="2" :step="0.1" :min="0" />
                </template>
              </el-table-column>
              <el-table-column v-if="columns.visible('endAmount')" prop="endAmount" label="截止值（元）">
                <template slot-scope="{row}">
                  <el-input-number :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                    style="width:100%" v-model="row.endAmount" :precision="2" :step="0.1" :min="0" />
                </template>
              </el-table-column>
              <el-table-column v-if="columns.visible('rebateRate')" prop="rebateRate" label="返点比例(%)">
                <template slot-scope="{row}">
                  <el-input-number :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                    style="width:100%" v-model="row.rebateRate" :precision="2" :step="0.1" :min="0" :max="100.00" />
                </template>
              </el-table-column>
              <el-table-column v-if="columns.visible('remark')" prop="remark" label="备注">
                <template slot-scope="{row}">
                  <el-input :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                    v-model="row.remark" placeholder="请输入备注"></el-input>
                </template>
              </el-table-column>
              <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" align="center">
                <template slot-scope="scope">
                  <el-button slot="reference" class="el-icon-delete opration_icon_btn"
                    :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                    style="border: none;width: auto;height: auto" @click="delAddRow(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-dialog  title="打印预览"
                destroy-on-close
                v-dialogDrag
                close-on-press-escape
                :visible.sync="showPdf" append-to-body width="50vw">
      <j-pdf :src="pdfSrc" ></j-pdf>
    </el-dialog>
    <el-dialog
      title="请选择打印模板"
      :visible.sync="crud.printConfig.pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="feeContract"
                    v-if="crud.printConfig.pringDialog"
                    @getPrintId="crud.detailedPrint"
                    :isPreview="crud.printConfig.isPreview"
      ></jPrintConfig>
    </el-dialog>
  </div>
</template>

<script>
import crudFeeContract from '@/api/erp/feeContract'
import crudContractRebate from '@/api/erp/feeContractRebate'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import ElSelectTree from 'el-select-tree'
import {getTree} from "@/api/erp/basSubject";
import {Notification} from "element-ui";
import {isEmpty} from "@/utils";
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '费用合同返点',
  url: 'api/feeContract/detail',
  sort: 'id,desc',
  params() {
    const href = location.href.split('/')
    if (href[5].includes('copyId')) {
      return {
        id: href[5].replace("copyId=", ""),
      }
    } else {
      return {
        id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1], page: 0, size: 999,
      }
    }
  },
  order: {
    feeContractRebateDto: {
      feeContractRebateReachDetailDtoList: [],
      feeContractRebateReachItemDtoList: []
    }
  },
  crudMethod: { ...crudFeeContract }
})
const defaultForm = {
  id: null,
  orderId: null,
  subjectId: null,
  subjectCode: null,
  subjectName: null,
  valueType: null,
  reachItem: null,
  seq: null,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null
}
export default {
  name: 'feeContractRebate',
  components: { pagination, crudOperation, rrOperation, udOperation, ElSelectTree, jPrintConfig },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['t_fee_order_type', 't_fee_contract_value_type', 't_fee_contract_reach_item', 't_fee_rebate_type', 'common_order_status'],
  data() {
    return {
      showPdf: false,
      permission: {
        add: ['admin', 'feeContract:add'],
        edit: ['admin', 'feeContract:edit'],
        del: ['admin', 'feeContract:del'],
        import: ['admin', 'feeContract:import'],
        export: ['admin', 'feeContract:export'],
        copy: ['admin', 'feeContract:copy'],
        upload: ['admin', 'feeContract:upload'],
        download: ['admin', 'feeContract:download'],
      },
      rules: {
        startDate: [
          { required: true, message: '合同开始时间不能为空', trigger: 'blur' }
        ],
        endDate: [
          { required: true, message: '合同结束时间不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '合同名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '合同类型不能为空', trigger: 'blur' }
        ],
        // subjectId: [
        //   {required: true, message: '费用科目不能为空', trigger: 'blur'}
        // ],
        // valueType: [
        //   {required: true, message: '取值对象不能为空', trigger: 'blur'}
        // ],
        // reachItem: [
        //   {required: true, message: '满足条件不能为空', trigger: 'blur'}
        // ],
      },
      id: null,
      confirmDialog: false,
      rebaseType: 'ladder',
      subjects: [],
      reachDetailList: "",
      loadingProjects: false
    }
  },
  watch: {},
  destroyed() {
    this.crud.setItemInfo("feeContractRebateDetail_add")
  },
  created() {
    this.getSubjects()
    if (this.$route.params.id == 'add') {
      if (this.crud.getItemInfo("feeContractRebateDetail_add")) {
        return false
      }
      this.crud.order = {
        feeContractRebateDto: {
          feeContractRebateReachDetailDtoList: [],
          feeContractRebateReachItemDtoList: []
        }
      }
    }
    if (window.location.href.includes('copy')){
      this.crud.order.createUserId = null
      this.crud.order.updateUserId = null
      this.crud.order.closeUserId = null
      this.crud.order.auditUserUserId = null
    }
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    [CRUD.HOOK.afterRefresh](crud, form) {
      if (this.$route.params.id == 'add') {
        crud.order = {
          feeContractRebateDto: {
            feeContractRebateReachDetailDtoList: [],
            feeContractRebateReachItemDtoList: []
          }
        }
      }
      if (this.$route.params.id != 'add') {
        this.getConditionProject(this.crud.order.feeContractRebateDto.reachItem, 1)
      }
      const href = location.href.split('/')
      if(href[5].includes('copyId')){
        this.crud.order.orderStatus = 'SAVE'
      }
      this.id = href[href.length - 1] == 'add' ? 0 : href[href.length - 1]
    },
    copyOrder(e) {
      this.crud.toCopy(this.crud.order.id,"/fee/feeContractGiftDetail")
    },
    submit() {
      this.$refs['orderForm'].validate(valid => {
        if (!valid) {
          return
        }
        if (this.crud.order.type == 1) {
          if (isEmpty(this.crud.order.supplierId) || this.crud.order.supplierId === 0) {
            Notification.error({ title: "供应商不能为空，请检查" })
            return
          }
        }
        if (this.crud.order.type == 2) {
          if (isEmpty(this.crud.order.customerId) || this.crud.order.customerId === 0) {
            Notification.error({ title: "客户不能为空，请检查" })
            return
          }
        }
        if (!this.tableRules(this.crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList, [], "请添加条件项目")) {
          return
        }
        var oDate1 = new Date(this.crud.order.startDate);
        var oDate2 = new Date(this.crud.order.endDate);
        if (oDate1.getTime() > oDate2.getTime()) {
          this.$message({
            message: '合同开始时间不能大于合同结束时间',
            type: 'warning'
          })
          return
        }
        let projectFlag = false
        let sumBateRate = 0.00
        if (this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList == null || this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList.length == 0) {
          Notification.error({ title: "【条件详情】不能为空，请检查" })
          return
        }
        for (let i = 0; i < this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList.length; i++) {
          const current = this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList[i]
          if (isNaN(current.startAmount)) {
            projectFlag = true
            Notification.error({ title: "【条件详情】起始值不能为空，请检查" })
            break
          }
          if (i < this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList.length && isNaN(current.endAmount)) {
            projectFlag = true
            Notification.error({ title: "【条件详情】当前行不是最后一行，结束值不能为空，请检查" })
            break
          }
          if (i > 0) {
            const prefix = this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList[i - 1]
            if (prefix.endAmount > current.startAmount) {
              Notification.error({ title: "【条件详情】结束值不能大于下一个的起始值，请检查" })
              projectFlag = true
              break
            }
          }
          sumBateRate += current.rebateRate
        }
        if (projectFlag) {
          return
        }
        if (sumBateRate > 100) {
          Notification.error({ title: "【条件详情】返点比例总和不能大于100%，请检查" })
          return
        }
        this.save()
      })
    },

    tableRules(list, rules, nullMsg) {
      let flag = true
      if (list === null || list.length === 0) {
        Notification.error({ title: nullMsg })
        return false
      }
      rules.forEach(rule => {
        for (let i = 0; i < list.length; i++) {
          if (list[i][rule.value] == undefined || list[i][rule.value] == null || list[i][rule.value] == '') {
            Notification.error({ title: '序号【' + (i + 1) + '】' + rule.name + '不能为空' })
            flag = false
            break
          }
        }
      })
      return flag
    },
    //保存
    save() {
      let that = this
      that.crud.loadingOpen()
      this.crud.order.project = 'rebate'
      const href = location.href.split('/')
      if (href[5].includes('copyId')) {
        this.crud.order.id = 0
        this.crud.order.feeContractRebateDto.id = null
        this.crud.order.feeContractRebateDto.orderIds = null
        for (let i = 0; i < this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList.length; i++) {
          this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList[i].id = null
          this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList[i].orderId = null
        }
        for (let i = 0; i < this.crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList.length; i++) {
          this.crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList[i].id = null
          this.crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList[i].orderId = null
        }
      }
      let params = this.crud.order
      if (this.crud.order.orderStatus === 'PASS')params.isEditWithoutReject = 1
      crudFeeContract.add(params).then(res => {
        if (res.success) {
          this.crud.order = res.data.order
          let id = this.crud.order.id
          if (this.$route.params.id == 'add' || href[5].includes('copyId')) {
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ params: { id } })
            this.crud.cleanItemInfo("feeContractRebateDetail_add")
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.loadingClose()
        } else {
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res) => {
        that.crud.loadingClose()
      })
    },
    getSubjects() {
      getTree().then(res => {
        this.subjects = []
        const subjects = { id: 0, name: '顶级分类', children: [] }
        subjects.children = res.data
        this.subjects.push(subjects)
      })
    },
    getConditionProject(item, type) {
      this.loadingProjects = true
      const params = {
        reachItem: item,
        type: type
      }
      crudContractRebate.getConditionProject(params).then(res => {
        this.loadingProjects = false
        if (res.success) {
          this.reachDetailList = JSON.stringify(res.data)
        } else {
          this.$message.error("获取条件项目失败")
        }
      })
    },
    addDetail() {
      const item = {}
      this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList.push(item)
    },
    delAddRow(i) {
      if (this.$route.params.id !== 'add') {
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList.splice(i, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.crud.order.feeContractRebateDto.feeContractRebateReachDetailDtoList.splice(i, 1)
      }
    },
    addProject() {
      if (!this.crud.order.feeContractRebateDto.reachItem) {
        this.$message.warning("请选择满足条件")
        return
      }
      const item = {}
      this.crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList.push(item)
    },
    changeReachGoods(e, row) {
      console.log(e)
      row.barcode = e.barcode
      row.goodsName = e.goodsName
      row.goodsCode = e.goodsCode
    },
    changeReachBrands(e, row) {
      row.barcode = e.barcode
      row.goodsBrandName = e.goodsBrandName
      row.goodsBrandCode = e.goodsBrandCode
    },
    genrateFeeOrder() {
      this.confirmDialog = true
    },
    confirmGenerate() {
      let that = this
      that.crud.loadingOpen()
      let ids = []
      ids.push(this.crud.order.id)
      crudFeeContract.generateFeeOrder(ids).then(res => {
        that.crud.loadingClose()
        if (res.status == 200) {
          let id = this.crud.order.id
          if (this.$route.params.id == 'add') {
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ params: { id } })
            this.crud.cleanItemInfo("feeContractRebateDetail_add")
          }
          this.confirmDialog = false
          this.$message.success('生成成功')
        } else {
          this.$message.success('生成失败')
        }
      }).catch(e => {
        that.crud.loadingClose()
        this.$message.success('生成失败')
      })
    },
    delProjectGoodsRow(i) {
      if (this.$route.params.id !== 'add') {
        this.$confirm('此操作将直接删除此条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList.splice(i, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.crud.order.feeContractRebateDto.feeContractRebateReachItemDtoList.splice(i, 1)
      }
    },
    changeSubjects(e) {
      this.crud.order.feeContractRebateDto.subjectCode = e.code
      this.crud.order.feeContractRebateDto.subjectName = e.name
    },
    changeSupplier(e) {
      this.crud.order.supplierId = e.id
      this.crud.order.supplierName = e.name
    },
    changeCustomer(e) {
      this.crud.order.customerId = e.id
      this.crud.order.customerName = e.name
    },
    changeReachItem(e) {
      this.getConditionProject(e, 1)
    },
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
